/**
 * @author hoang.pt
 * @version $Id: MultiProblem.java 143 2010-09-07 04:51:29Z phantichhoang $
 */

package homework.homework2.problem1;

/**
 * Display Fibo number
 * 
 * @author hoang.pt
 */
class Thread1 implements Runnable {

	/**
     *
     */
	Fibonaci fiboObj;

	/**
	 * 
	 */
	Thread t;
	
	/**
	 * 
	 * @param f
	 */
	public Thread1(Fibonaci f) {
		this.fiboObj = f;
		
		//init thread and start
		t = new Thread(this);
		t.start();
	}

	/**
	 * run
	 */
	@Override
	public void run() {
		
		//run forever
		while (true) {
			synchronized (fiboObj) {
				//thread 1 not visited
				while(!fiboObj.flag) {
					// change flag
					fiboObj.flag = true;					

					fiboObj.displayFibo();
				}
			}
		}
	}
}

/**
 * Check odd and even
 * 
 * @author hoang.pt
 */
class Thread2 implements Runnable {

	/**
	 * 
	 */
	Fibonaci fiboObj;

	/**
	 * 
	 */
	Thread t;
	
	
	/**
	 * 
	 * @param f
	 */
	public Thread2(Fibonaci f) {
		this.fiboObj = f;
		
		//init thread and start
		t = new Thread(this);
		t.start();
	}

	/**
     *
     */
	@Override
	public void run() {
		while (true) {
			// synchronise
			synchronized (fiboObj) {
				while (fiboObj.flag) {
					// change flag
					fiboObj.flag = false;

					// display current fibo
					fiboObj.displayOddAndEven();
					
					//change fibo
					fiboObj.changeState();
				}
			}
		}
	}
}

/**
 * @author hoang.pt
 * 
 */
public class MultiProblem {

	/**
     *
     */
	public MultiProblem() {
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// init Fibo number
		Fibonaci f = new Fibonaci();

		// init thread 1 and start
		Thread1 r1 = new Thread1(f);

		// init thread 2 and start
		Thread2 r2 = new Thread2(f);


		// joining
		try {
			r1.t.join();
			r2.t.join();
		} catch (InterruptedException ex) {
		}
	}
}
